import axios from 'axios';
import qs from 'qs';
import {
  getCookie
} from '@/utils/cookie'
import {
  Toast
} from 'vant';

/** 
 * 提示函数 
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
  Toast({
    message: msg,
    duration: 2000,
    forbidClick: true
  });
}

//创建axios实例
var instance = axios.create({
  timeout: 1000 * 12
});
instance.defaults.baseURL = '/api'
instance.defaults.withCredentials = true
instance.defaults.crossDomain = true
// 设置post请求头
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';


instance.interceptors.request.use(
  config => {
    const token = getCookie('MUSIC_U'); //获取Cookie
    token && (config.headers.Authorization = token);
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


// 拦截响应数据：
instance.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (err) {
  if (err && err.response) {
    // 如果有返回的错误信息，则直接提示错误信息
    if (err.response.data.message) {
      tip(err.response.data.message)
    };
    if (err.response.data.msg) {
      tip(err.response.data.msg)
    };
    // 否则根据状态码来判断：
    switch (err.response.status) {

      case 400:
        err.message = '昵称不符合规范';
        break;
      case 401:
        err.message = '未授权，请重新登录(401)';
        break;
      case 403:
        err.message = '拒绝访问(403)';
        break;
      case 404:
        err.message = '请求出错(404)';
        break;
      case 408:
        err.message = '操作过于频繁';
        break;
      case 500:
        err.message = '服务器错误(500)';
        break;
      case 501:
        err.message = '服务未实现(501)';
        break;
      case 502:
        err.message = '网络错误(502)';
        break;
      case 503:
        err.message = '验证码错误';
        break;
      case 504:
        err.message = '网络超时(504)';
        break;
      case 505:
        err.message = '该昵称已被占用';
        break;
      default:
        err.message = `连接出错(${err.response.status})!`;
    }
  } else {
    err.message = '连接服务器失败!'
  }
  return Promise.reject(err);
});

export function get(url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}
export function post(url, params) {
  return new Promise((resolve, reject) => {
    instance.post(url, qs.stringify(params))
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}


// export default instance
